<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="客户名字" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名字"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户身份证号" prop="customerNumber">
        <el-input
          v-model="queryParams.customerNumber"
          placeholder="请输入客户身份证号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户手机号" prop="customerPhonenumber">
        <el-input
          v-model="queryParams.customerPhonenumber"
          placeholder="请输入客户手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bank:grey:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bank:grey:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bank:grey:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入灰名册</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bank:grey:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="greyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="客户编号" align="center" prop="customerId" />
      <el-table-column label="客户名字" align="center" prop="customerName" />
      <el-table-column label="身份证号" align="center">
        <template slot-scope="scope">
          {{ scope.row.customerNumber.substring(0, 6) + '********' + scope.row.customerNumber.substring(14) }}
        </template>
      </el-table-column>

      <el-table-column label="客户手机号" align="center" prop="customerPhonenumber" />
      <el-table-column label="客户标签备注" align="center" prop="customerNotes" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bank:grey:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bank:grey:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改灰名册管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="客户名字" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户名字" />
        </el-form-item>
        <el-form-item label="客户身份证号" prop="customerNumber" >
          <el-input v-model="form.customerNumber" placeholder="请输入客户身份证号" maxlength="18" :disabled="form.customerId != null"/>
        </el-form-item>
        <el-form-item label="客户手机号" prop="customerPhonenumber">
          <el-input v-model="form.customerPhonenumber" placeholder="请输入客户手机号" maxlength="11"/>
        </el-form-item>
        <el-form-item label="客户标签备注" prop="customerNotes">
          <el-input v-model="form.customerNotes" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGrey, getGrey, delGrey, addGrey, updateGrey } from "@/api/bank/grey";
import {getToken} from "@/utils/auth";
import {listVillagers} from "@/api/bank/villagers";
import {getDomicileByNumber} from "@/api/bank/domicile";
import {updateDomicile} from "@/api/bank/domicile";

export default {
  name: "Grey",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 灰名册管理表格数据
      greyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/bank/grey/importData" // todo
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerName: null,
        customerNumber: null,
        customerPhonenumber: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        customerName: [
          { required: true, message: "客户名字不能为空", trigger: "blur" }
        ],
        customerNumber: [
          { required: true, message: "客户身份证号不能为空", trigger: "blur" },
          { min: 18, max: 18, message: "客户身份证号必须是18位", trigger: "blur" }
        ],
        customerPhonenumber: [
          { required: true, message: "客户手机号不能为空", trigger: "blur" },
          { min: 11, max: 11, message: "手机号必须是11位", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    async updatadomicile() {
      try {
        // 获取灰名册列表和村民信息列表
        const greyResponse = await listGrey({pageSize: 10000000});
        const greyList = greyResponse.rows;
        const villagersResponse = await listVillagers({pageSize: 100000000});
        const villagersList = villagersResponse.rows;

        for (const greyItem of greyList) {
          const matchedVillager = villagersList.find(villager => villager.villagerNumber === greyItem.customerNumber);

          if (matchedVillager) {
            // 找到匹配的村民信息，获取对应的户籍信息
            const domicileResponse = await getDomicileByNumber(matchedVillager.villagerDomicileNumber);
            const domicileInfo = domicileResponse.data;

            // 使用updateDomicile接口修改户籍信息
            await updateDomicile({
              domicileId: domicileInfo.domicileId,
              domicileLabel: "2" // 设置户籍标签为“2”
            });

            console.log(`Updated domicile info for villager number ${matchedVillager.villagerNumber}`);
          }
        }
      } catch (error) {
        console.error("Error updating domicile info:", error);
      }
    },

    /** 查询灰名册管理列表 */
    getList() {
      this.loading = true;
      listGrey(this.queryParams).then(response => {
        this.greyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        customerId: null,
        customerName: null,
        customerNumber: null,
        customerPhonenumber: null,
        customerNotes: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.customerId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加灰名册管理";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const customerId = row.customerId || this.ids
      getGrey(customerId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改灰名册管理";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.customerId != null) {
            updateGrey(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.updatadomicile().then(() => {
                // 在户籍信息更新和插入完成后，再次获取村民列表信息
                this.getList();
              }).catch(error => {
                console.error("更新户籍信息失败:", error);
              });
            });
          } else {
            addGrey(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.updatadomicile().then(() => {
                // 在户籍信息更新和插入完成后，再次获取村民列表信息
                this.getList();
              }).catch(error => {
                console.error("更新户籍信息失败:", error);
              });
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const customerIds = row.customerId || this.ids;
      this.$modal.confirm('是否确认删除灰名册管理编号为"' + customerIds + '"的数据项？').then(function() {
        return delGrey(customerIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bank/grey/export', {
        ...this.queryParams
      }, `grey_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "灰名册导入"; // todo
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('bank/grey/importTemplate', {
      }, `stu_grey_template_${new Date().getTime()}.xlsx`)  // todo
    },
// 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
// 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.updatadomicile().then(() => {
        // 在户籍信息更新和插入完成后，再次获取村民列表信息
        this.getList();
      }).catch(error => {
        console.error("更新户籍信息失败:", error);
      });
    },
// 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    }
  }
};
</script>
